/**
 * 个人资料路由 - Expo Router
 * 用户个人资料页面，显示学习统计、设置和成就
 */
import React, { useState, useEffect, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  Alert,
  RefreshControl,
} from 'react-native';
import { useFocusEffect, useRouter } from 'expo-router';
import AsyncStorage from '@react-native-async-storage/async-storage';

// 导入自定义组件
import { ProfileHeader } from '../components/Headers';
import { UserProgressCard, StatisticsGrid, AchievementsList, SettingsMenu, BottomTip } from '../components/ScreenComponents';

/**
 * 个人资料组件 - 用户个人信息和设置页面
 */
export default function ProfileScreen() {
  const router = useRouter();
  
  const [userProgress, setUserProgress] = useState({
    currentStreak: 0,
    totalXP: 0,
    lessonsCompleted: 0,
    completedLessons: [],
    achievements: [],
    lastStudyDate: null,
  });
  
  const [refreshing, setRefreshing] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  /**
   * 从本地存储加载用户进度数据
   */
  const loadUserProgress = async () => {
    try {
      const [xpData, streakData, completedData, achievementsData, lastDateData] = await Promise.all([
        AsyncStorage.getItem('totalXP'),
        AsyncStorage.getItem('currentStreak'),
        AsyncStorage.getItem('completedLessons'),
        AsyncStorage.getItem('achievements'),
        AsyncStorage.getItem('lastStudyDate'),
      ]);

      const totalXP = xpData ? parseInt(xpData) : 0;
      const currentStreak = streakData ? parseInt(streakData) : 0;
      const completedLessons = completedData ? JSON.parse(completedData) : [];
      const achievements = achievementsData ? JSON.parse(achievementsData) : [];
      const lastStudyDate = lastDateData || null;

      setUserProgress({
        totalXP,
        currentStreak,
        lessonsCompleted: completedLessons.length,
        completedLessons,
        achievements,
        lastStudyDate,
      });
    } catch (error) {
      console.error('加载用户进度失败:', error);
      Alert.alert('错误', '加载数据失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  /**
   * 下拉刷新处理函数
   */
  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await loadUserProgress();
    setRefreshing(false);
  }, []);

  /**
   * 设置项点击处理函数
   */
  const handleSettingPress = (settingKey) => {
    switch (settingKey) {
      case 'clearData':
        Alert.alert(
          '确认重置',
          '确定要清除所有学习进度吗？此操作不可撤销。',
          [
            { text: '取消', style: 'cancel' },
            {
              text: '确认重置',
              style: 'destructive',
              onPress: async () => {
                try {
                  await AsyncStorage.multiRemove([
                    'totalXP',
                    'currentStreak',
                    'completedLessons',
                    'achievements',
                    'lastStudyDate',
                  ]);
                  
                  setUserProgress({
                    currentStreak: 0,
                    totalXP: 0,
                    lessonsCompleted: 0,
                    completedLessons: [],
                    achievements: [],
                    lastStudyDate: null,
                  });
                  
                  Alert.alert('成功', '学习进度已重置');
                } catch (error) {
                  Alert.alert('错误', '重置失败，请重试');
                }
              },
            },
          ]
        );
        break;
      default:
        Alert.alert('提示', '该功能正在开发中...');
    }
  };

  // 页面焦点时加载数据
  useFocusEffect(
    useCallback(() => {
      loadUserProgress();
    }, [])
  );

  useEffect(() => {
    loadUserProgress();
  }, []);

  if (isLoading) {
    return (
      <View style={styles.container}>
        <ProfileHeader 
          username="学习者"
          userStats={{ currentStreak: 0, totalXP: 0 }}
        />
        <View style={styles.loadingContainer}>
          <Text style={styles.loadingText}>加载中...</Text>
        </View>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      {/* 个人资料头部组件 */}
      <ProfileHeader 
        username="学习者"
        userStats={{
          currentStreak: userProgress.currentStreak,
          totalXP: userProgress.totalXP
        }}
      />

      {/* 滚动内容区域 */}
      <ScrollView 
        style={styles.scrollView}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            colors={['#6C63FF']}
            tintColor="#6C63FF"
          />
        }
        showsVerticalScrollIndicator={false}
      >
        {/* 用户进度卡片 */}
        <UserProgressCard 
          userProgress={userProgress}
          username="学习者"
          style={styles.progressCard}
        />

        {/* 统计信息网格 */}
        <StatisticsGrid 
          userProgress={userProgress}
          style={styles.statsGrid}
        />

        {/* 成就列表 */}
        <View style={styles.sectionHeader}>
          <Text style={styles.sectionTitle}>我的成就</Text>
          <Text style={styles.sectionSubtitle}>查看已解锁的成就徽章</Text>
        </View>

        <AchievementsList 
          achievements={userProgress.achievements}
          userProgress={userProgress}
          style={styles.achievementsList}
        />

        {/* 设置菜单 */}
        <View style={styles.sectionHeader}>
          <Text style={styles.sectionTitle}>设置</Text>
          <Text style={styles.sectionSubtitle}>个性化您的学习体验</Text>
        </View>

        <SettingsMenu 
          onSettingPress={handleSettingPress}
          style={styles.settingsMenu}
        />

        {/* 底部提示信息 */}
        <BottomTip 
          icon="person-outline"
          text="完善个人资料，获得更好的学习体验！"
          style={styles.bottomTip}
        />
      </ScrollView>
    </View>
  );
}

/**
 * 样式定义
 */
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f8f9fa',
  },
  
  scrollView: {
    flex: 1,
  },

  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f8f9fa',
  },

  loadingText: {
    fontSize: 16,
    color: '#666',
    fontFamily: 'System',
  },

  progressCard: {
    marginHorizontal: 16,
    marginTop: 16,
    marginBottom: 12,
  },

  statsGrid: {
    marginHorizontal: 16,
    marginBottom: 16,
  },

  sectionHeader: {
    marginHorizontal: 16,
    marginVertical: 12,
  },

  sectionTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 4,
    fontFamily: 'System',
  },

  sectionSubtitle: {
    fontSize: 16,
    color: '#666',
    fontFamily: 'System',
  },

  achievementsList: {
    marginHorizontal: 16,
    marginBottom: 16,
  },

  settingsMenu: {
    marginHorizontal: 16,
    marginBottom: 16,
  },

  bottomTip: {
    marginHorizontal: 16,
    marginVertical: 20,
  },
});